<?php
$host = 'localhost';
$username = '';
$password = '';
$dbname = '';
$id = $_POST['id'];
$reader_id = $_POST['reader_id'];
$url1 = "homepage.html";
$mysql = new mysqli($host, $username, $password, $dbname);
if ($mysql->connect_errno) {
    die('数据库连接失败：' . $mysql->connect_errno);
} else {
    $sql1 = "SELECT book_id,reader_id from b_r where book_id=$id and reader_id=$reader_id";
    $result1 = $mysql->query($sql1);
    $row = mysqli_fetch_row($result1);
    if ($result1 && $row[0] == $id && $row[1] == $reader_id) { //这本书的确在借
        $sql2 = "DELETE from b_r where book_id=$id and reader_id=$reader_id"; //清除b_r表记录
        $result2 = $mysql->query($sql2);
        $sql3 = "SELECT on_shelf,num from bookinfo where book_id=$id"; //更改bookinfo表信息
        $result3 = $mysql->query($sql3);
        $row1 = mysqli_fetch_row($result3); //row1[0]=on_shelf=是/否，row1[1]=num=0/...
        if ($row1[0] == '否' || $row1[1] == 0) { //这本书归还之前已经没有了
            $sql4 = "UPDATE bookinfo SET on_shelf='是',num=num+1 where book_id=$id";
            $result4 = $mysql->query($sql4);
            if ($result4) {
                echo "<script>alert('归还成功')</script>";
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url1'"; //跳转到首页
                echo "</script>";
                $mysql->close();
            } else {
                echo "<script>alert('归还失败')</script>";
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url1'"; //跳转到首页
                echo "</script>";
                $mysql->close();
            }
        } else { //归还之前这本书还在架
            $sql5 = "UPDATE bookinfo SET num=num+1 where book_id=$id";
            $result5 = $mysql->query($sql5);
            if ($result5) {
                echo "<script>alert('归还成功')</script>";
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url1'"; //跳转到首页
                echo "</script>";
                $mysql->close();
            } else {
                echo "<script>alert('归还失败')</script>";
                echo "<script language='javascript' type='text/javascript'>";
                echo "window.location.href='$url1'"; //跳转到首页
                echo "</script>";
                $mysql->close();
            }
        }
    } else {
        echo "<script>alert('归还失败,因为没有这本书或者这本书没有被借')</script>";
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$url1'"; //跳转到首页
        echo "</script>";
        $mysql->close();
    }
}
